/*
 * Unidata Platform Community Edition
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 * This file is part of the Unidata Platform Community Edition software.
 *
 * Unidata Platform Community Edition is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Unidata Platform Community Edition is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

package org.unidata.mdm.meta.service.impl.data.validation;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.springframework.stereotype.Component;
import org.unidata.mdm.core.service.CustomPropertiesSupport;
import org.unidata.mdm.meta.type.model.attributes.SearchableMetaModelAttribute;
import org.unidata.mdm.meta.type.model.entities.Entity;
import org.unidata.mdm.system.exception.ValidationResult;

@Component
public class RegisterValidator extends AbstractDataModelElementValidator<Entity> implements CustomPropertiesSupport {

    @Nonnull
    @Override
    public DataModelElementType getSupportedElementType() {
        return DataModelElementType.REGISTER;
    }

    @Nullable
    @Override
    public String getModelElementId(@Nonnull Entity modelElement) {
        return modelElement.getName();
    }

    @Override
    public Collection<ValidationResult> checkElement(Entity el) {

        Collection<ValidationResult> errors = new ArrayList<>();

        errors.addAll(super.checkElement(el));
        errors.addAll(super.checkEntitiesGroupValue(el.getGroupName(), el.getDisplayName()));
        errors.addAll(super.checkTopLevelNameStopList(el.getName(), el.getDisplayName()));

        el.getSimpleAttribute().forEach(attr -> errors.addAll(checkSimpleAttribute(attr, el.getDisplayName())));

        boolean mainDisplayableSet = el.getSimpleAttribute().stream()
                .anyMatch(SearchableMetaModelAttribute::isMainDisplayable);

        errors.addAll(super.checkMainDisplayableState(mainDisplayableSet, el.getDisplayName()));
        errors.addAll(super.checkValidityPeriod(el.getValidityPeriod(), el.getDisplayName()));
        errors.addAll(validateCustomProperties(el.getDisplayName(), el.getCustomProperties()));

        return errors;
    }
}
